const { documentService } = require('../services/docs.service');

function wrap(handler) {
  return async (req, res, next) => {
    try {
      await handler(req, res, next);
    } catch (error) {
      next(error);
    }
  };
}

const create = wrap(async (req, res) => {
  const doc = await documentService.createDocument(req.body);
  res.status(201).json({ ok: true, doc });
});

const list = wrap(async (req, res) => {
  const docs = await documentService.listDocuments(req.query.limit, req.query.offset);
  res.json({ count: docs.length, docs });
});

const getById = wrap(async (req, res) => {
  const doc = await documentService.getDocument(req.params.id);
  if (!doc) {
    res.status(404).json({ error: 'not_found', message: 'Document not found' });
    return;
  }
  res.json({ doc });
});

const update = wrap(async (req, res) => {
  const doc = await documentService.updateDocument(req.params.id, req.body);
  if (!doc) {
    res.status(404).json({ error: 'not_found', message: 'Document not found' });
    return;
  }
  res.json({ ok: true, doc });
});

const remove = wrap(async (req, res) => {
  const removed = await documentService.deleteDocument(req.params.id);
  if (!removed) {
    res.status(404).json({ error: 'not_found', message: 'Document not found' });
    return;
  }
  res.status(204).send();
});

const searchByText = wrap(async (req, res) => {
  const tags = req.query.tags ? req.query.tags.split(',').filter(Boolean) : [];
  const results = await documentService.searchDocuments({
    query: req.query.q,
    limit: req.query.limit,
    tags
  });
  res.json({ count: results.length, results });
});

const searchByVector = wrap(async (req, res) => {
  const results = await documentService.searchByVector(req.body.vector, req.body.limit);
  res.json({ count: results.length, results });
});

const updateVector = wrap(async (req, res) => {
  const doc = await documentService.updateVector(req.params.id, req.body.vector);
  if (!doc) {
    res.status(404).json({ error: 'not_found', message: 'Document not found' });
    return;
  }
  res.json({ ok: true, doc });
});

module.exports = {
  docsController: {
    create,
    list,
    getById,
    update,
    remove,
    searchByText,
    searchByVector,
    updateVector
  }
};
